package com.jeecg.p3.system.poster.web;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.alipay.api.domain.Person;
import com.jeecg.p3.base.util.*;
import com.jeecg.p3.system.advisor.entity.StudyAdviser;
import com.jeecg.p3.system.advisor.service.StudyAdvService;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Course;
import com.jeecg.p3.system.entity.JwSystemUser;
import com.jeecg.p3.system.poster.entity.*;
import com.jeecg.p3.system.poster.service.*;
import com.jeecg.p3.system.service.CourseService;
import com.jeecg.p3.system.service.JwSystemUserService;
import com.jeecg.p3.system.util.Constants;
import com.jeecg.p3.system.util.HtmlUtil;
import com.jeecg.p3.system.util.QRCodeUtils;
import com.jeecg.p3.system.util.UuidUtils;
import com.jeecg.p3.system.vo.LoginUser;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageList;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 海报管理控制层
 */
@Controller
@RequestMapping("/system/back/poster/manage")
public class PosterController extends BaseController {
    public final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PosterService service;
    @Autowired
    private PosterTypeService posterTypeService;
    @Autowired
    private JwSystemUserService userService;//用户处理层
    @Autowired
    private StudyAdvService studyAdvService;//学习顾问处理层
    @Autowired
    private PosterManagerService pmService;//海报统计管理处理层
    @Autowired
    private WhitePersonService whitePersonService;//白名单处理层
    @Autowired
    private BlackPersonService blackPersonService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private ExamQuestionService examQuestionService;

    /**
     * 获取微信用户信息
     * @param response
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/getWxUserInfo")
    public AjaxJson getWxUserInfo(HttpServletResponse response, HttpServletRequest request) throws
            IOException {
        AjaxJson j = new AjaxJson();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        if(wxUserInfo == null) {
            j.setSuccess(false);
            j.setMsg("获取微信授权失败！");
            return j;
        } else {
            j.setMsg("获取微信授权成功！");
            j.setObj(wxUserInfo);
        }
        return j;
    }



    /**
     * 微信获取用户授权
     * @param response
     */
    @RequestMapping("/authorize")
    public void authorize(HttpServletResponse response) {
        String backUrl = ComCode.systemUrl + "/system/back/poster/manage/callback.do";
        String url = null;
        try {
            url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri=" + URLEncoder.encode(backUrl, "UTF-8")
                    + ComCode.userinfoUrl;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询微信用户回调
     * @param httpServletResponse
     * @param httpServletRequest
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/callback")
    public AjaxJson callBack(HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) throws
            IOException {
        AjaxJson j = new AjaxJson();
        String code = httpServletRequest.getParameter("code");
        logger.info("code   ---->" + code);
        if (StringUtils.isNotEmpty(code)) {
            String url = ComCode.getCodeUrl + "appid=" + ComCode.appid + "&secret=" + ComCode.secret + "&code=" + code
                    + "&grant_type=authorization_code";
            String tokenString = HttpUtil.get(url);
            logger.info("tokenString  --->  " + tokenString);
            if (StringUtils.isNotEmpty(tokenString)) {
                JSONObject json = new JSONObject(tokenString);
                String access_token = json.getStr("access_token");
                String openid = json.getStr("openid");
                logger.info("access_token--->" + access_token + ",  openid-----> " + openid);

                if (StringUtils.isNotEmpty(access_token) && StringUtils.isNotEmpty(openid)) {
                    String userUrl = ComCode.getUserInfo + "access_token=" + access_token
                            + "&openid=" + openid + "&lang=zh_CN";
                    String userInfo = HttpUtil.get(userUrl);
                    if (StringUtils.isNotEmpty(userInfo)) {
                        JSONObject userJson = new JSONObject(userInfo);
                        WxUserInfo wxUserInfo = new WxUserInfo(openid, userJson.getStr("nickname"), userJson.getStr("sex"),
                                userJson.getStr("province"), userJson.getStr("city"), userJson.getStr("country"),
                                userJson.getStr("headimgurl"), userJson.getStr("privilege"), userJson.getStr("unionid"));
                        logger.info("wxUserInfo---------->" + wxUserInfo.toString());
                        j.setObj(wxUserInfo);
                        return j;
                    }
                }
            }
        }

        j.setSuccess(false);
        j.setMsg("获取微信授权失败！");
        return j;
    }


    /**
     * 加载引导页
     * @param request
     * @param response
     * @param posterNo
     */
    @RequestMapping(value="/getPoster.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void getPoster(HttpServletRequest request, HttpServletResponse response, String posterNo) {
        try {
            Poster poster = service.findByNo(posterNo);
            if(poster == null) {
                return;
            }
            WxUserInfo wxUserInfo = getWxUserInfo(request);
            String toUrl = ComCode.systemUrl + "/system/back/poster/manage/getPoster.do?posterNo=" + posterNo;
            if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
                AjaxJson j = WxUtils.getWxUserDetail(request);
                if(j.isSuccess()) {
                    wxUserInfo = (WxUserInfo) j.getObj();
                    request.getSession().setAttribute(Constants.wxInfo, j.getObj());
                } else {
                    String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                            + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                    response.sendRedirect(url);
                    return;
                }
            }
            BlackPerson blackPerson = new BlackPerson();
            blackPerson.setOpenId(wxUserInfo.getOpenid());
            List<BlackPerson> blackPeoples = blackPersonService.findByParam(blackPerson);
            if(blackPeoples != null && blackPeoples.size() > 0) {
                logger.info(wxUserInfo.getOpenid() + "------黑名单用户禁止访问！！！");
                return;
            }
            /*String code = request.getParameter("code");
            if(StringUtils.isNotEmpty(code)) {
                logger.info("------检测到有code进行再次跳转！！！");
                response.sendRedirect(toUrl);
                return;
            }*/
            VelocityContext velocityContext = new VelocityContext();
            /****************此处代码为添加最新群******************************/
            if(!ComCode.statusNormal.equals(poster.getIsNew())) {
                Poster param = new Poster();
                param.setIsNew(ComCode.statusNormal);
                param.setUserId(poster.getUserId());
                List<Poster> list = service.findByParam(param);
                if(list != null && list.size() > 0) {
                    poster = list.get(0);
                }
            }
            /****************此处代码为添加最新群******************************/
            velocityContext.put("poster",poster);
            String viewName = "system/back/poster/guide.html";
            ViewVelocity.view(request,response,viewName,velocityContext);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载落地海报,根据id查询海报信息，获取微信的openid，如果用户是白名单或者不是白名单但未加群，则查看群码，如果用户不是白名单，
     * 且已加群则返回个人落地海报码
     * @param request
     * @param response
     * @param pId 海报id
     */
    @RequestMapping(value="/loadLandPoster.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void loadLandPoster(HttpServletRequest request, HttpServletResponse response, String pId) {
        try {
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/poster/land_poster.html";
            AjaxJson j = WxUtils.getWxUserOpenId(request);
            if(j.isSuccess()) {
                String openId = j.getObj().toString();
                WhitePerson whitePerson = new WhitePerson();
                whitePerson.setStatus("1");
                whitePerson.setOpenId(openId);
                Poster poster = service.findById(Long.valueOf(pId));
                Integer pcount = whitePersonService.count(whitePerson);
                PosterManager pm = new PosterManager();
                pm.setPosterId(pId);
                pm.setStudyOpenId(openId);
                pm.setStatus("1");
                if (pcount > 0) {
                    velocityContext.put("picUrl",poster.getLandGroupPicUrl());//白名单显示落地群码
                    pm.setStuAdvId(poster.getUserId());
                    pm.setCreateDate(DateUtil.dateToString(new Date()));
                    pm.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
                    pmService.doAdd(pm);
                } else {
                    Integer pmCount = pmService.count(pm);
                    if(pmCount > 0) {
                        velocityContext.put("picUrl",poster.getLandPicUrl());//不是白名单且已经进入过则展示人码
                    } else {
                        velocityContext.put("picUrl",poster.getLandGroupPicUrl());//不是白名单且未进群则展示群码
                        pm.setStuAdvId(poster.getUserId());
                        pm.setCreateDate(DateUtil.dateToString(new Date()));
                        pm.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
                        pmService.doAdd(pm);
                    }
                }
            } else {
                viewName = "base/back/common/error.vm";
                velocityContext.put("errorMsg", "获取微信授权失败！！！");
            }
            ViewVelocity.view(request,response,viewName,velocityContext);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }



    /**
     *
     * @param query 海报查询对象
     * @param request
     * @param response
     * @param pageNo 第几页
     * @param pageSize 页数大小
     * @throws Exception
     */
    @RequestMapping(value="/list.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void toIndividual(@ModelAttribute Poster query, HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        PageQuery<Poster> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        VelocityContext velocityContext = new VelocityContext();
        LoginUser user = getCurrentUser(request);
        query.setIsNew("1");
        if(!isAdmin(request)) {
            //不是管理员只查询自己的海报
            StudyAdviser adviser = studyAdvService.findByUserNumber(user.getUserId());
            query.setUserId(adviser.getId());
        }
        pageQuery.setQuery(query);
        velocityContext.put("poster",query);
        PageList<Poster> posterPageList = service.queryPageList(pageQuery);
        for (Poster p :posterPageList.getValues()) {
            if(p != null && StringUtils.isNotEmpty(p.getSharePicUrl())) {
                p.setSharePicUrl(p.getSharePicUrl().replace("\\","/"));
            }
        }
        velocityContext.put("pageInfos", SystemTools.convertPaginatedList(posterPageList));
        if(isMobile(request)) {
            String viewName = "system/back/app/my_poster.html";
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            String viewName = "system/back/poster/poster.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 跳转到H5我的海报管理
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/toMyList.do",method = {RequestMethod.GET,RequestMethod.POST})
    public void myList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        VelocityContext velocityContext = new VelocityContext();
        String viewName = "system/back/app/my_poster.html";
        ViewVelocity.view(request,response,viewName,velocityContext);
    }
    /**
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getData",method ={RequestMethod.GET, RequestMethod.POST})
    public Map<String, Object> getData(HttpServletRequest request, @ModelAttribute Poster query,
        @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
        @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize)
    {
        Map<String, Object> map = new HashMap<>();
        PageQuery<Poster> pageQuery = new PageQuery<>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        LoginUser user = getCurrentUser(request);
        StudyAdviser adviser = studyAdvService.findByUserNumber(user.getUserId());
        query.setUserId(adviser.getId());
        query.setIsNew("1");
        pageQuery.setQuery(query);
        PageList<Poster> posterPageList = service.queryPageList(pageQuery);
        for (Poster p :posterPageList.getValues()) {
            if(p != null && StringUtils.isNotEmpty(p.getSharePicUrl())) {
                p.setSharePicUrl(p.getSharePicUrl().replace("\\","/"));
            }
        }
        map.put("pageInfos", posterPageList);
        return map;
    }

    /**
     * 跳转到新增海报界面页面
     * @return
     */
    @RequestMapping(value = "/toAdd",method ={RequestMethod.GET, RequestMethod.POST})
    public void toAddDialog(HttpServletRequest request, HttpServletResponse response, ModelMap model)throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        JwSystemUser u= new JwSystemUser();
        u.setAdmin("0");//查询人员类型为学习顾问
        u.setUserStat(Constants.USER_NORMAL_STATE);//人员状态为正常
        List<JwSystemUser> users = userService.findStudyAdviser(u);
        velocityContext.put("users", users);
        velocityContext.put("isAdmin", isAdmin(request));
        String viewName = "system/back/poster/poster_add.vm";
        if(isMobile(request)) {
            viewName = "system/back/poster/poster_add_h5.html";
        }
        ViewVelocity.view(request,response,viewName,velocityContext);
    }

    /**
     * 保存海报信息
     * @return
     */
    @RequestMapping(value = "/doAdd",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doAdd(@ModelAttribute Poster poster, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser loginUser = getCurrentUser(request);
            String id = UuidUtils.getId();
            poster.setCreateDate(DateUtil.dateToString(new Date()));
            poster.setCreateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            poster.setCreateUser(loginUser.getId());
            poster.setStatus(ComCode.statusNormal);
            JwSystemUser user = null;
            if(StringUtils.isNotEmpty(poster.getUserId())) {
                user = userService.queryById(Long.valueOf(poster.getUserId()));
            } else {
                user = userService.queryById(Long.valueOf(loginUser.getId()));
            }
            StudyAdviser adviser = studyAdvService.findByUserNumber(user.getUserId());
            poster.setUserId(adviser.getId().toString());
            poster.setUserGroupId(adviser.getGroupId());
            poster.setUserGroupName(adviser.getGroupName());
            poster.setUserName(user.getUserName());
            poster.setPosterNo(id);
            //1.生成分享海报
            String fenxiangMa = createPosterFenxiang(request, "fenxiangma", user.getUserId(),
                    ComCode.systemUrl + "/system/back/poster/manage/getPoster.do?posterNo=" + id, poster.getPosterType());
            poster.setSharePicUrl(fenxiangMa);
            //2.生成落地群海报
            if(StringUtils.isNotEmpty(poster.getWxGroupCode())) {
                String luodiqunma = createPosterLuodi(request, poster.getWxGroupCode(), "luodiqunma_" + user.getUserId() + ".jpg");
                poster.setLandGroupPicUrl(luodiqunma);
            }
            //3.生成落地个人海报
            if(StringUtils.isNotEmpty(poster.getWxPersonCode())) {
                String luodipersonma = createPosterLuodi(request, poster.getWxPersonCode(), "luodirenma_" + user.getUserId() + ".jpg");
                poster.setLandPicUrl(luodipersonma);
            }
            service.doAdd(poster);
            j.setMsg("保存成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("保存失败");
            e.printStackTrace();
        }
        return j;
    }

    /**
     *
     * @param request
     * @param type 海报类型：fenxiang分享海报，luodi落地海报
     * @param userName 用户编码
     * @return
     */
    private String createPosterFenxiang(HttpServletRequest request, String type, String userName, String text, String postType) {
        LoginUser user = (LoginUser) request.getSession().getAttribute(Constants.OPERATE_WEB_LOGIN_USER);
        String pathUrl = "";
        try {
            String fileUrl = ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.poster;
            String fileDir = uploadConfig.getUploadPath() + user.getId() + ComCode.poster;
            String fileName = type + "_" + userName + ".jpg";
            String hbName = "fxhb_" + userName + ".jpg";
            UploadUtil.createDirectory(fileDir);//创建文件夹
            File newFile = UploadUtil.getAvailableFile(fileDir + fileName, 0);//判断文件名是否重复
            String realName = newFile.getName();//真正名称
            String haibaoma = QRCodeUtils.encode(text, null, fileDir + realName, false);//文件实际保存地址
            File newHbFile = UploadUtil.getAvailableFile(fileDir + hbName, 0);
            String hbRealName = newHbFile.getName();
            //HtmlUtil.convertImg(ComCode.defaultFenxiang, haibaoma, fileDir + hbRealName);

            PosterType pt = this.posterTypeService.findByCode(postType);
            HtmlUtil.convertImage(pt.getBackPath(), pt.getBackWidth(), pt.getBackHeight(),
                    haibaoma,  pt.getQrCodeWidth(), pt.getQrCodeHeight(),
                    pt.getxPositon(), pt.getyPositon(), fileDir + hbRealName);
            pathUrl =  fileUrl + hbRealName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pathUrl;
    }

    /**
     * 生成落地海报
     * @param request
     * @param path
     * @param name
     * @return
     */
    private String createPosterLuodi(HttpServletRequest request, String path, String name) {
        LoginUser user = (LoginUser) request.getSession().getAttribute(Constants.OPERATE_WEB_LOGIN_USER);
        String fileUrl = ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.poster;
        String fileDir = uploadConfig.getUploadPath() + user.getId() + ComCode.poster;
        String realPath = path.substring((ComCode.separator + uploadConfig.getStaticPath()).length(), path.length());//获取图片保存的相对路径
        File newHbFile = UploadUtil.getAvailableFile(fileDir + name, 0);
        String hbName = newHbFile.getName();
        PosterType pt = this.posterTypeService.findByCode("ldhb01");
        HtmlUtil.convertImage(pt.getBackPath(), pt.getBackWidth(), pt.getBackHeight(),
                uploadConfig.getUploadPath() + realPath,  pt.getQrCodeWidth(), pt.getQrCodeHeight(),
                pt.getxPositon(), pt.getyPositon(), fileDir + hbName);
        //HtmlUtil.convertImg1(ComCode.defaultLuodi, uploadConfig.getUploadPath() + realPath,
        //        fileDir + hbName);
        return  fileUrl + hbName;
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="/toEdit",method = RequestMethod.GET)
    public void toEdit(@RequestParam(required = true, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        Poster poster = service.findById(id);
        velocityContext.put("poster",poster);
        if(isMobile(request)) {
            LoginUser user = getCurrentUser(request);
            String viewName = "system/back/poster/poster_modify.html";//海报为空则跳转到列表界面去添加

            velocityContext.put("user", user);
            ViewVelocity.view(request,response,viewName,velocityContext);
        } else {
            JwSystemUser u= new JwSystemUser();
            u.setAdmin("0");//查询人员类型为学习顾问
            u.setUserStat(Constants.USER_NORMAL_STATE);//人员状态为正常
            List<JwSystemUser> users = userService.findStudyAdviser(u);
            velocityContext.put("users", users);
            velocityContext.put("isAdmin", isAdmin(request));
            String viewName = "system/back/poster/poster_edit.vm";
            ViewVelocity.view(request,response,viewName,velocityContext);
        }
    }

    /**
     * 跳转到编辑页面
     * @return
     */
    @RequestMapping(value="/toModify",method = RequestMethod.GET)
    public void toModify(@RequestParam(required = false, value = "id" ) Long id,HttpServletResponse response,HttpServletRequest request) throws Exception{
        VelocityContext velocityContext = new VelocityContext();
        LoginUser user = getCurrentUser(request);
        if(!isAdmin(request)) {
            StudyAdviser adviser = this.studyAdvService.findByUserNumber(user.getUserId());
            Poster param = new Poster();
            param.setUserId(adviser.getId());
            param.setIsNew("1");
            List<Poster> list = service.findByParam(param);
            if(list == null || list.size() == 0) {
                velocityContext.put("user", user);
                String viewName = "system/back/poster/poster_modify.html";//海报为空则跳转到列表界面去添加
                ViewVelocity.view(request,response,viewName,velocityContext);
            }
            if(list.size() == 1) {
                String viewName = "system/back/poster/poster_modify.html";//海报为空则跳转到列表界面去添加
                Poster poster = list.get(0);
                velocityContext.put("poster",poster);
                velocityContext.put("user", user);
                ViewVelocity.view(request,response,viewName,velocityContext);
            } else {
                toIndividual(new Poster(), request,response, 1, 10);
            }
        } else {
            toIndividual(new Poster(), request,response, 1, 10);
        }
    }


    /**
     * 编辑海报，删除原有海报，生成新的海报！
     * @param poster
     * @param request
     * @return
     */
    @RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute Poster poster, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            Poster newPoster = new Poster();
            newPoster.setUserId(poster.getUserId());
            newPoster.setWxGroupCode(poster.getWxGroupCode());
            newPoster.setWxPersonCode(poster.getWxPersonCode());
            newPoster.setGuide(poster.getGuide());
            newPoster.setLevel(poster.getLevel());
            newPoster.setPosterType(poster.getPosterType());
            this.doAdd(newPoster, request);
            if(StringUtils.isNotEmpty(poster.getId())) {
                this.service.updateIsOld(poster);
            }
            //this.doDelete(Long.valueOf(poster.getId()), request);
            //service.doDelete(poster);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }
    /**
     * 保存修改数据初版
     * @return
     */
    /*@RequestMapping(value = "/doEdit",method ={RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxJson doEdit(@ModelAttribute Poster poster, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            Poster old = service.findById(Long.valueOf(poster.getId()));
            if(StringUtils.isNotEmpty(old.getWxGroupCode()) && !old.getWxGroupCode().equals(poster.getWxGroupCode())) {
                if(StringUtils.isNotEmpty(poster.getWxGroupCode())) {
                    String luodiqunma = createPosterLuodi(request, poster.getWxGroupCode(), "luodiquanma" + user.getUserId() + ".jpg");
                    poster.setLandGroupPicUrl(luodiqunma);
                }
            }
            if(StringUtils.isNotEmpty(old.getWxPersonCode()) && !old.getWxPersonCode().equals(poster.getWxPersonCode())) {
                if(StringUtils.isNotEmpty(poster.getWxPersonCode())) {
                    String luodipersonma = createPosterLuodi(request, poster.getWxPersonCode(), "luodiquanma" + user.getUserId() + ".jpg");
                    poster.setLandPicUrl(luodipersonma);
                }
            }
            String fenxiangMa = createPosterFenxiang(request, "fenxiangma", user.getUserId(),
                    ComCode.systemUrl + "/system/back/poster/manage/getPoster.do?posterNo=" + old.getPosterNo());
            poster.setSharePicUrl(fenxiangMa);
            poster.setUpdateDate(DateUtil.dateToString(new Date()));
            poster.setUpdateTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            poster.setUpdateUser(user.getId());
            this.service.doEdit(poster);
            j.setMsg("编辑成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("编辑失败");
        }
        return j;
    }*/


    /**
     * 删除
     * @return
     */
    @RequestMapping(value="/doDelete",method = RequestMethod.GET)
    @ResponseBody
    public AjaxJson doDelete(@RequestParam(required = true, value = "id" ) Long id, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
        try {
            LoginUser user = getCurrentUser(request);
            Poster poster = service.findById(id);
            poster.setDeleteDate(DateUtil.dateToString(new Date()));
            poster.setDeleteTime(DateUtil.dateToString(new Date(), "HH:mm:ss"));
            poster.setDeleteUser(user.getId());
            service.doDelete(poster);
            j.setMsg("删除成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            j.setSuccess(false);
            j.setMsg("删除失败:"+e.getMessage());
        }
        return j;
    }

    /**
     * 头像上传
     * 保存图片
     * @return
     */
    @RequestMapping(value = "/doUpload",method ={RequestMethod.POST})
    @ResponseBody
    public AjaxJson doUpload(MultipartHttpServletRequest request, HttpServletResponse response, MultipartFile file){
        LoginUser user = (LoginUser) request.getSession().getAttribute(Constants.OPERATE_WEB_LOGIN_USER);
        AjaxJson j = new AjaxJson();
        try {
            String fileUrl =  ComCode.separator + uploadConfig.getStaticPath() + ComCode.separator + user.getId() + ComCode.poster;
            String fileDir = uploadConfig.getUploadPath()  + user.getId() + ComCode.poster;
            if(!file.isEmpty()) {
                String fileName = file.getOriginalFilename();
                UploadUtil.createDirectory (fileDir);
                String filePath = fileDir + fileName;
                File newFile = UploadUtil.getAvailableFile (filePath, 0);
                file.transferTo (newFile);
                j.setObj(fileUrl + newFile.getName ());
                j.setMsg("保存成功");
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("保存失败");
        }
        return j;
    }

    /**
     * 查询我的海报
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMyPoster",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson modifyPwd(HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        try {
            if(isAdmin(request)) {
                j.setMsg("管理员没有海报!");
                return j;
            }
            LoginUser loginUser = getCurrentUser(request);
            if(loginUser == null) {
                j.setSuccess(false);
                j.setMsg("请登录后再做处理！");
                return j;
            }
            JwSystemUser u = userService.queryById(Long.valueOf(loginUser.getId()));
            Poster param = new Poster();
            param.setUserId(u.getId().toString());
            List<Poster> list = service.findByParam(param);
            Map<String, Object> map = new HashMap<>();
            map.put("list", list);
            j.setObj(map);
            j.setMsg("查询海报成功！");
        } catch (Exception e) {
            j.setMsg("查询海报异常！");
            j.setSuccess(false);
            e.printStackTrace();
        }
        return j;
    }

    /**
     * 查询课程详情
     * @param id
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getProductDetail",method ={RequestMethod.GET, RequestMethod.POST})
    public AjaxJson getProductDetail(@RequestParam(required = true, value = "id" ) Long id, HttpServletRequest request) {
        AjaxJson j = new AjaxJson();
        Course course = courseService.queryById(id);
        ExamQuestion param = new ExamQuestion();
        param.setCourse(course);
        List<ExamQuestion> examQuess = examQuestionService.findByParam(param);
        if(examQuess != null && examQuess.size() == 1) {
            ExamQuestion examQuestion = examQuess.get(0);
            course.setExamQues(examQuestion);
        }
        if(course == null) {
            j.setSuccess(false);
            j.setMsg("暂无该课程信息！");
            return j;
        } else {
            j.setSuccess(true);
            j.setMsg("查询成功！");
            j.setObj(course);
            return j;
        }
    }

}
